package com.broheim.websocket.spring.config;


import com.broheim.websocket.core.endpoint.server.WebSocketServer;
import com.broheim.websocket.core.listener.Listener;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class WebSocketConfigRegisterBean implements InitializingBean, ApplicationContextAware {

    private ApplicationContext applicationContext;

    @Override
    public void afterPropertiesSet() throws Exception {
        ListenerRegisterBean registerBean = applicationContext.getBean(ListenerRegisterBean.class);
        if (null != registerBean) {
            Map<String, Set<Listener>> register = registerBean.getRegister();
            Iterator<Map.Entry<String, Set<Listener>>> iterator = register.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, Set<Listener>> entry = iterator.next();
                entry.getValue().forEach(listener -> {
                    WebSocketServer.registerListener(entry.getKey(), listener);
                });
            }
        }

    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
